package com.ticket.system.service.impl;

import com.ticket.common.core.redis.RedisCache;
import com.ticket.common.utils.DateUtils;
import com.ticket.common.utils.StringUtils;
import com.ticket.system.domain.Yanchu;
import com.ticket.system.domain.YanchuAttach;
import com.ticket.system.domain.vo.GroupCollectVo;
import com.ticket.system.domain.vo.YanchuCollectVo;
import com.ticket.system.mapper.YanchuMapper;
import com.ticket.system.service.IYanchuAttachService;
import com.ticket.system.service.IYanchuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 演出Service业务层处理
 * 
 * @author gjchen
 * @date 2023-04-03
 */
@Service
public class YanchuServiceImpl implements IYanchuService 
{
    @Autowired
    private YanchuMapper yanchuMapper;

    @Autowired
    private IYanchuAttachService yanchuAttachService;

    @Autowired
    private RedisCache redisCache;

    private static final Logger log = LoggerFactory.getLogger(YanchuServiceImpl.class);

    /**
     * 查询演出
     * 
     * @param id 演出主键
     * @return 演出
     */
    @Override
    public Yanchu selectYanchuById(Long id)
    {
        return yanchuMapper.selectYanchuById(id);
    }

    /**
     * 查询演出列表
     * 
     * @param yanchu 演出
     * @return 演出
     */
    @Override
    public List<Yanchu> selectYanchuList(Yanchu yanchu)
    {
        String dateYanchu = yanchu.getDateYanchu();
        if(StringUtils.isNotEmpty(dateYanchu)){
            if(dateYanchu.indexOf("-")<=0){
                throw new RuntimeException("必填参数不能为空！");
            }
        }
        return yanchuMapper.selectYanchuList(yanchu);
    }

    @Override
    public YanchuCollectVo selectYanchuListCollect(Yanchu yanchu)
    {
        String dateYanchu = yanchu.getDateYanchu();
        if(StringUtils.isNotEmpty(dateYanchu)){
            if(dateYanchu.indexOf("-")<=0){
                throw new RuntimeException("必填参数不能为空！");
            }
        }
        return yanchuMapper.selectYanchuListCollect(yanchu);
    }


    /**
     * 查询集团演出列表
     *
     * @param yanchu 演出
     * @return 演出
     */
    @Override
    public List<Yanchu> selectGroupYanchuList(Yanchu yanchu)
    {
        String dateYanchu = yanchu.getDateYanchu();
        if(StringUtils.isNotEmpty(dateYanchu)){
            if(dateYanchu.indexOf("-")<=0){
                throw new RuntimeException("必填参数不能为空！");
            }
        }
        return yanchuMapper.selectGroupYanchuList(yanchu);
    }

    @Override
    public List<Yanchu> selectGroupList(Yanchu yanchu)
    {
        String dateYanchu = yanchu.getDateYanchu();
        if(StringUtils.isNotEmpty(dateYanchu)){
            if(dateYanchu.indexOf("-")<=0){
                throw new RuntimeException("必填参数不能为空！");
            }
        }

        return yanchuMapper.selectGroupList(yanchu);
    }
    @Override
    public List<GroupCollectVo> selectGroupListRollup(Yanchu yanchu)
    {
        String dateYanchu = yanchu.getDateYanchu();
        if(StringUtils.isNotEmpty(dateYanchu)){
            if(dateYanchu.indexOf("-")<=0){
                throw new RuntimeException("必填参数不能为空！");
            }
        }

        return yanchuMapper.selectGroupListRollup(yanchu);
    }


    public List<YanchuCollectVo> selectYanchuCollectList(){
        return yanchuMapper.selectYanchuCollectList();
    }

    public List<YanchuCollectVo> selectYanchuPiaowuTotal(){
        return yanchuMapper.selectYanchuPiaowuTotal();
    }

    public List<YanchuCollectVo> selectYanchuShouruTotal(){
        return yanchuMapper.selectYanchuShouruTotal();
    }

    /**
     * 新增演出
     * 
     * @param yanchu 演出
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertYanchu(Yanchu yanchu)
    {
        String riqi = yanchu.getDateYanchu();
        if(StringUtils.isEmpty(riqi)){
            throw new RuntimeException("演出日期不能为空");
        }
        Date date = DateUtils.parseDate(riqi);
        if(null==date){
            throw new RuntimeException("日期格式不正确");
        }

        if(null==yanchu.getBiliPiaowu()){
            throw new RuntimeException("票务分成比例不能为空！");
        }
        if(yanchu.getBiliPiaowu().doubleValue()<0){
            throw new RuntimeException("票务分成比例必须大于等于0");
        }

        if(null!=yanchu.getChangciYanchu()){
            BigDecimal multiply = yanchu.getChangciYanchu().multiply(new BigDecimal(100));
            BigDecimal[] bigDecimals = multiply.divideAndRemainder(new BigDecimal(25));
            if(bigDecimals[1].compareTo(new BigDecimal(0)) > 0){
                throw new RuntimeException("场次数量必须是0.25的倍数！");
            }
        }
        SimpleDateFormat getYearFormat = new SimpleDateFormat("yyyy");
        String currentYear = getYearFormat.format(date);
        yanchu.setYearYanchu(currentYear);
        getYearFormat = new SimpleDateFormat("MM");
        String currentMon = getYearFormat.format(date);
        yanchu.setMonthYanchu(Integer.valueOf(currentMon));

        SimpleDateFormat getYearMonFormat = new SimpleDateFormat("yyyyMM");
        String yearMon = getYearMonFormat.format(date);
        Integer serial = redisCache.getCacheObject("serialNo:"+yearMon);
        log.info("serialNo redis:{} {}",yanchu.getNameYanchu(),serial);
        if(null == serial){
            serial = 1;
            redisCache.setCacheObject("serialNo:"+yearMon,serial.intValue(),360, TimeUnit.DAYS);
        }else{
            serial = redisCache.redisTemplate.opsForValue().increment("serialNo:"+yearMon).intValue();
        }
        if(serial<100){
            yanchu.setSerialNo(yearMon+StringUtils.padl(serial,3));
        }else{
            yanchu.setSerialNo(yearMon+serial);
        }
        log.info("serialNo:{} {}",yanchu.getNameYanchu(),yanchu.getSerialNo());

        int count = yanchuMapper.insertYanchu(yanchu);
        if(count > 0 && !CollectionUtils.isEmpty(yanchu.getYanchuAttachs())){
            yanchu.getYanchuAttachs().forEach(item -> {
                if(null != item){
                    item.setIdYanchu(yanchu.getId().intValue());
                    item.setCreateBy(yanchu.getCreateBy());
                }
            });
            yanchuAttachService.insertBatchYanchuAttach(yanchu.getYanchuAttachs());
        }

        return count;
    }

    /**
     * 修改演出
     * 
     * @param yanchu 演出
     * @return 结果
     */
    @Override
    public int updateYanchu(Yanchu yanchu)
    {
        String riqi = yanchu.getDateYanchu();
        Date date = DateUtils.parseDate(riqi);
        if(null==date){
            throw new RuntimeException("日期格式不正确");
        }

        if(null==yanchu.getBiliPiaowu()){
            throw new RuntimeException("票务分成比例不能为空！");
        }
        if(yanchu.getBiliPiaowu().doubleValue()<0){
            throw new RuntimeException("票务分成比例必须大于等于0");
        }
        SimpleDateFormat getYearFormat = new SimpleDateFormat("yyyy");
        String currentYear = getYearFormat.format(date);
        yanchu.setYearYanchu(currentYear);
        getYearFormat = new SimpleDateFormat("MM");
        String currentMon = getYearFormat.format(date);
        yanchu.setMonthYanchu(Integer.valueOf(currentMon));
        int count = yanchuMapper.updateYanchu(yanchu);
        if(count > 0 && !CollectionUtils.isEmpty(yanchu.getYanchuAttachs())){
            for(YanchuAttach attach : yanchu.getYanchuAttachs()){
                if(null == attach){
                    continue;
                }
                attach.setIdYanchu(yanchu.getId().intValue());
                if(null != attach.getId() && attach.getId() != 0){
                    yanchuAttachService.updateYanchuAttach(attach);
                }else{
                    yanchuAttachService.insertYanchuAttach(attach);
                }
            }
        }
        return count;
    }

    /**
     * 批量删除演出
     * 
     * @param ids 需要删除的演出主键
     * @return 结果
     */
    @Override
    public int deleteYanchuByIds(Long[] ids)
    {
        return yanchuMapper.deleteYanchuByIds(ids);
    }
    @Override
    public int shenbaoYanchuByIds(Long[] ids)
    {
        return yanchuMapper.shenbaoYanchuByIds(ids);
    }
    @Override
    public int shenbaoCancelByIds(Long[] ids)
    {
        return yanchuMapper.shenbaoCancelByIds(ids);
    }


    /**
     * 删除演出信息
     * 
     * @param id 演出主键
     * @return 结果
     */
    @Override
    public int deleteYanchuById(Long id)
    {
        return yanchuMapper.deleteYanchuById(id);
    }
}
